<template>
  <div class="clearfix" >
    <a-upload
      :accept="accept"
      :remove="handleRemove"
      listType="picture-card"
      :fileList="fileList"
      @preview="handleImgPreview"
      @change="handleImgChange"
      :customRequest="customRequest"
      :openFileDialogOnClick="false"
    >
      <div v-if="fileList.length < fileLength" @click="uploadClick">
        <a-icon type="plus" />
        <div class="ant-upload-text">签名</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleImgCancel">
      <img :alt="decodeURIComponent(previewImageName)" style="width: 100%" :src="previewImage" />
    </a-modal>
    <a-modal :visible="sign.show"  title="请通过鼠标签名" :bodyStyle="{padding:0}"
             :confirm-loading="importLoading"
             @cancel="()=>sign.show=false"
              @ok="handleGenerate">
        <vue-esign ref="esign" :height="500">

        </vue-esign>

    </a-modal>
  </div>
</template>


<script>
  import {isURL} from '../../utils/validate';
  import {appApiBaseUrl} from '../../config/constant.config';
  import {concatUrl, randomUUID} from '../../utils/util';
  import {getAction,uploadFile} from "../../api/manage";
  import {common, } from "../../api/url";
  import vueEsign from 'vue-esign'
  import AkFilePreview from './file-preview/AkFilePreview'
  export default {
    name: 'AkSign',
    props: {
      value: {
        type: String,
        default: '',
        required: false
      },
      disabled:{
        type:Boolean,
        default:false,
        required:false,
      },
      // 上传分组类型
      type:String,
      // 文件类型上传长度
      fileLength:{
        type: Number,
        default: 10,
        required: false
      },

    },
    components:{ AkFilePreview, vueEsign},
    data:function() {
      return{
        importPercent:0,//上传百分
        importLoading:false, //正在上传
        accept:'*',
        // 预览可见
        previewVisible: false,
        // 预览url
        previewImage: '',
        // 预览文件名
        previewImageName:'',
        fileList: [],
        baseUrl:'',
        // val:''
        sign:{
          show:false,
        }

      }
    },

    mounted(){
     this.baseUrl = concatUrl(appApiBaseUrl,common.fileBaseUrl);
     if(this.value){
       this.fileList = this.handleFileListStringToFileList(this.value);
     }else{
       this.fileList = [];
     }
     getAction(common.fileUploadTypeUrl, {type:this.type})
       .then(res=>{
         if(res.success){
           this.accept=res.result;
         }
       })

    },
    watch: {
      value (val) {
        if(val){
          this.fileList=this.handleFileListStringToFileList(val);
        }else{
          this.fileList =[];
        }

      },
  // :openFileDialogOnClick="fileList.length < fileLength"
    },
    methods:{
      uploadClick(){
        if(!this.disabled){
          this.importLoading = false;
          this.sign.show = true;
          this.handleReset();
        }

      },
      handleReset () {
        if(this.$refs.esign){
          this.$refs.esign.reset()
        }

      },
      handleGenerate () {
        this.importLoading = true;
        this.$refs.esign.generate().then(res => {
          console.log(res);
          let arr = res.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          let file = new File([u8arr], randomUUID()+".png", { type: mime });
          this.customRequest({file})
        }).catch(err => {
          alert(err) // 画布没有签字时会执行这里 'Not Signned'
        })
      },
      customRequest(request){
        console.log(request)
        let url = common.fileUploadUrl;

        let file = request.file;
        let formData = new FormData();

        let filename = request.filename;
        if(!filename){
          filename = 'file';
        }
        formData.append(filename, file);
        formData.append("type", this.type);
        if (request.data) {
          for (let key in request.data) {
            formData.append(key,request.data[key])
          }
        }
        this.importLoading = true;
        uploadFile(url, formData, (event)=>{
          console.log(event);

          if(event.total){
            this.importPercent = event.loaded/event.total*100;
          }
        }).then(res=>{
          if(res.success){
            this.$message.success('文件上传成功');
            res.result.forEach(t=>{
              this.fileList.push({
                uid: randomUUID(),
                name: t,
                status: 'done',
                url: isURL(url)?url:concatUrl(this.baseUrl,t),
              });
            });

            this.handleImgChange(this.fileList);
            this.sign.show = false;
          }
        })
          .finally(()=>{
            this.importLoading = false;
          });
      },
      // doUpload(){
      //   let that = this;
      //   window.CKFinder.modal( {
      //     chooseFiles: true,
      //     width: 800,
      //     height: 600,
      //     resourceType:that.type,
      //     onInit: function( finder ) {
      //       finder.on( 'files:choose', function( evt ) {
      //         var file = evt.data.files.first();
      //         // var name = file.attributes.name;
      //         var url = file.attributes.url;
      //
      //         that.fileList.push({
      //           uid: url,
      //           name: url,
      //           status: 'done',
      //           url: isURL(url)?url:concatUrl(that.baseUrl,url),
      //         });
      //
      //         that.handleImgChange(that.fileList);
      //       } );
      //
      //
      //     }
      //   } );
      //   return false;
      // },
      handleRemove(file){
        if(this.disabled){
          this.$message.warning("此文件不允许删除");
          return ;
        }
        this.fileList.indexOf(file);
        return !this.disabled;
      },
      handleFileListStringToFileList(val){
        let fileArray = [];
        let urlArrays = val.split(",");
        let that = this;
        for (let i = 0; i < urlArrays.length; i++) {
          if (urlArrays[i]) {
            fileArray.push({
              uid: urlArrays[i],
              name: urlArrays[i],
              status: 'done',
              url: isURL(urlArrays[i])?urlArrays[i]:concatUrl(that.baseUrl,urlArrays[i]),
            });
          }

        }
        return fileArray;
      },
      handleImgCancel() {
        this.previewVisible = false;
      },
      handleImgPreview(file) {
        this.previewImage = file.url || file.thumbUrl;
        this.previewImageName = file.name;
        this.previewVisible = true;
      },
      handleImgChange(fileList) {

        if( Array.isArray(fileList)){
          this.fileList = fileList;
        }else if(typeof fileList == 'object'){
         this.fileList = fileList.fileList;
        }
        console.log(this.fileList)
        let val = "";
        if(this.fileList.length > 0){
          let i=0
          for(; i<this.fileList.length;i ++){
            let file = this.fileList[i];
            if(file.url){
              val = val+file.name+",";
            }else if(file.response  &&  file.response.success){
              val = val + file.response.result.name+","
            }
          }
        }
        if(val.length>0 && val.endsWith(",")){
          val = val.substring(0, val.length-1);
        }

        this.$emit('change', val);
      },
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style scoped>

</style>
